package com.zhenmaitang.clinic_sys.security;

import com.zhenmaitang.clinic_sys.entity.User;
import com.zhenmaitang.clinic_sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public CustomUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 将用户角色列表转换为GrantedAuthority集合
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (user.getRole() != null && !user.getRole().isEmpty()) {
            for (String role : user.getRole()) {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
            }
        }

        return new CustomUserDetails(
                user.getUsername(),
                user.getPassword(),
                user.getEnabled(),
                authorities,
                user.getId() // 传递用户ID
        );
    }
}